package com.example.demo.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Objects;

//这里 TextWebSocketFrame 类型，表示一个文本帧(frame)
@ChannelHandler.Sharable

public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<Object> {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static RandomAccessFile file;

    static {
        try {
//            multiResolutionImage = new BaseMultiResolutionImage();
            file = new RandomAccessFile("data.txt", "rw");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //当web客户端连接后， 触发方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户加入聊天的信息推送给其它在线的客户端
        /*
        该方法会将 channelGroup 中所有的channel 遍历，并发送 消息，
        我们不需要自己遍历
         */
        channelGroup.add(channel);
        channelGroup.forEach(ch -> ch.writeAndFlush(new TextWebSocketFrame("[客户端]"+channelGroup.size())));
        //id 表示唯一的值，LongText 是唯一的 ShortText 不是唯一
        System.out.println("handlerAdded 被调用" + ctx.channel().id().asLongText());
        System.out.println("handlerAdded 被调用" + ctx.channel().id().asShortText());
    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> ch.writeAndFlush(new TextWebSocketFrame("[客户端]离开了"+channelGroup.size())));
        System.out.println("channelGroup size" + channelGroup.size());
        System.out.println("handlerRemoved 被调用" + ctx.channel().id().asLongText());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        TextWebSocketFrame msg1 =(TextWebSocketFrame)msg;
        String str1 = msg1.text();
        String str2 = str1 + "\n\n";
        System.out.println(!Objects.equals(str1, "0"));
        //这时我们遍历channelGroup, 根据不同的情况，回送不同的消息
channelGroup.forEach(ch -> {
//    if (channel != ch) { //不是当前的channel,转发消息
        if (!Objects.equals(str1, "0")) {
            System.out.println("服务器收到消息 " + str1);
            ch.writeAndFlush(new TextWebSocketFrame(str2));
            System.out.println(!Objects.equals(str1, "0"));
        }
//    } else {
//        if (!Objects.equals(str1, "0")) {
//            System.out.println("服务器收到消息 " +str1 );
//            ch.writeAndFlush("用户："+str1 + "\n\n");
//            System.out.println(!Objects.equals(str1, "0"));
//        }
        else {
            ch.writeAndFlush(new TextWebSocketFrame("[客户端]" + channelGroup.size()));
            System.out.println("服务器收到消息 " + str1);}
//        }}
});

        if (msg instanceof TextWebSocketFrame){
            if (!Objects.equals(str1, "0")) {
    file.seek(file.length()); String str="\r\n";
    file.write(((TextWebSocketFrame) msg).text().getBytes());
    file.write(str.getBytes());}System.out.println("服务器收到消息 " + str1);
    //回复消息
}
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生 " + cause.getMessage());
        ctx.close(); //关闭连接
    }


}
